package com.chen.cos;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(value = "/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String url = "jdbc:mysql://localhost:3306/cosplay_community?serverTimezone=UTC";
        String db_name = "root";
        String db_pass = "13574178580";


        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            try (Connection conn = DriverManager.getConnection(url, db_name, db_pass)) {
                String sql = "SELECT * FROM user WHERE username = ? AND password_hash = ?";

                try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                    stmt.setString(1, username);
                    stmt.setString(2, password);

                    ResultSet rs = stmt.executeQuery();

                    if (rs.next()) {
                        // 登录成功
                        response.sendRedirect("index.jsp");
                    } else {
                        // 登录失败
                        response.setContentType("text/html;charset=UTF-8");
                        PrintWriter out = response.getWriter();
                        out.println("<script>alert('用户名或密码错误');history.back();</script>");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=UTF-8");
            try {
                PrintWriter out = response.getWriter();
                out.println("<script>alert('系统异常，请稍后重试');history.back();</script>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }


    }
}
